/**
 * Created by kevin on 2017/6/12.
 */
var fs = require('fs');
var path = require('path');

var dataPath = path.resolve('./data');

var logPath = dataPath + '/log';


function mkdirsSync(dirname) {
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return true;
        }
    }
}

// type 1 : 打包  2 : 模块
function writeStream(type,platform,filename) {
    this.filename = filename;
    var typePath = type === 1 ? '/packages' : (type === 2 ? '/components' : '/other');
    var platFormPath = platform === 1 ? '/ios' : '/android';
    this.filepath = path.join(logPath ,typePath ,platFormPath);

    mkdirsSync(this.filepath);

    this.ws = fs.createWriteStream(path.join(this.filepath,this.filename));

    this.write = function(data) {

        if (data) {
            this.ws.write(data.toString(),'UTF8');
        }
    };

    this.end = function () {
        this.ws.end();
    };
}

function readStream(type,platform,filename,callback) {
    this.filename = filename;
    var typePath = type === 1 ? '/packages' : (type === 2 ? '/components' : '/other');
    var platFormPath = platform === 1 ? '/ios' : '/android';
    this.filepath = path.join(logPath ,typePath ,platFormPath);

    mkdirsSync(this.filepath);
    this.rs = fs.createReadStream(path.join(this.filepath,this.filename));

    this.rs.setEncoding('UTF8');

    this.rs.on('data', function(chunk) {
        callback(false,null,chunk);
    });

    this.rs.on('end',function(){
        callback(true,null,null);
    });

    this.rs.on('error',function(err){
        callback(true,err,null);
    });

}

module.exports.readStream = readStream;

module.exports.writeStream = writeStream;